﻿package src.com.online.rpg
{
	import src.com.online.rpg.input.InputManager;
	import flash.events.Event;
	import flash.ui.Keyboard;
		
	/*
	 * Player
	 */
	public class Player extends AnimatedGameObject
	{
		private var _direction:String;
		private var _invulnerabilityTime:Number;
		
		private var _vx:Number;
		private var _vy:Number;
		
		private var _dead:Boolean;
		
		public function Player() 
		{
			super( new Grandma );
			
			// start with some invincibility
			_invulnerabilityTime = 2.0;
			
			_vx = 0; _vy = 0;
		}
		
		public override function update(dt:Number):void
		{
			super.update(dt);	// update animation
			
			if (_dead) return;
			
			// dirFlags keeps track of which direction we have pressed
			var dirFlags:uint = 0;
			
			if (InputManager.isKeyDown(Keyboard.RIGHT))	dirFlags |= 0x1;
			if (InputManager.isKeyDown(Keyboard.LEFT))	dirFlags |= 0x2;
			if (InputManager.isKeyDown(Keyboard.DOWN))	dirFlags |= 0x4;
			if (InputManager.isKeyDown(Keyboard.UP))	dirFlags |= 0x8;
			
			// suppress opposing directions
			if ((dirFlags & 0x3) == 0x3) dirFlags &= ~0x3;
			if ((dirFlags & 0xc) == 0xc) dirFlags &= ~0xc;
			
			var animationName:String;
			
			if (dirFlags)
			{
				animationName = "walk";
				
				// figure out the direction animation we should use
				_direction = "";
				if (dirFlags & 0x4) _direction += "Down";
				if (dirFlags & 0x8) _direction += "Up";
				if (dirFlags & 0x3) _direction += "Right";
				
				// flip the appropriate direction
				if (dirFlags & 0x1)		_movieClip.scaleX = 1;
				else if(dirFlags & 0x2)	_movieClip.scaleX = -1;
				
				// set our velocity
				if (dirFlags & 0x1) _vx = 180;
				if (dirFlags & 0x2) _vx = -180;
				if (dirFlags & 0x4) _vy = 100;
				if (dirFlags & 0x8) _vy = -100;
				
				// alter our speed based on the animation frame
				if (!checkAnimationFlag("moving"))
				{
					_vx *= .25;
					_vy *= .25;
				}
			}
			else
			{
				// we're not moving
				animationName = "idle";
				_vx = _vy = 0;
			}
			
			// use the direction-specific animation
			animationName += _direction;
			changeAnimation(animationName, false);
			
			// move!
			x += _vx * dt;
			y += _vy * dt;
			
			if (_invulnerabilityTime > 0)
			{
				_invulnerabilityTime -= dt;
				_graphics.visible = uint(_invulnerabilityTime / .1) % 2 == 0;	// blinking
			}
			
			depth = y;
		}
		
		public function die():void
		{
			// never die if invincible!
			if (_invulnerabilityTime > 0 || _dead) return;
			
			_dead = true;
			changeAnimation("dead");
			depth = 999;
			
			addEventListener(GameEvent.ANIMATION_COMPLETE, onDeathComplete);
		}
		
		private function onDeathComplete(e:Event):void
		{
			dispatchEvent(new Event(GameEvent.PLAYER_DIED));
		}
		
	}

}